package com.xuetang9.fujian;

import com.xuetang9.fujian.utils.JdbcUtil;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/17 22:05
 * @version: V1.0
 * @package: com.xuetang9.fujian
 **/
public class DataBaseViewer extends Application {
    private ComboBox<String> cmbDataBase  = new ComboBox<String>();
    private ComboBox<String> cmbTables  = new ComboBox<String>();
    @Override
    public void start(Stage primaryStage) throws Exception {
        FlowPane pane =new FlowPane();
        pane.setAlignment(Pos.CENTER);
        pane.getChildren().addAll(cmbDataBase,cmbTables);
        initEvent();
        Scene scene = new Scene(pane,400,200);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initEvent() {
        cmbDataBase.setValue("所有数据库");
        try(Connection connection = JdbcUtil.GetConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet catalogs = metaData.getCatalogs();
            while (catalogs.next()){
                cmbDataBase.getItems().add(catalogs.getString(1));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        cmbDataBase.setOnAction(event -> {
            cmbTables.getItems().clear();
            String DBName = cmbDataBase.getSelectionModel().getSelectedItem();
            try (Connection connection = JdbcUtil.GetConnection()){
                ResultSet tables = connection.getMetaData().getTables(DBName, null, null, new String[]{"TABLE","SYSTEM TABLE"});
                while (tables.next()){
                    cmbTables.getItems().add(tables.getString("table_name"));
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}
